#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <maminjie2@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

method_def gitpush gitpushforce

git_curbranch() {
    git symbolic-ref --short -q HEAD
}

# git_checklocalrepo
#   Check whether the current directory is a git repo
# Returns:
#   0 - yes
#   !0 - no
git_checklocalrepo() {
    git rev-parse --is-inside-work-tree &>/dev/null
}

# git_checklocalbranch branch
#   Check whether the branch is in the local git repo
# Returns:
#   0 - yes
#   !0 - no
git_checklocalbranch() {
    if [ $# -ne 1 ]; then
        return 1
    fi
    local branch="$1"
    local exist=$(git branch | sed -r 's/^\s+|^\*+\s+//g' | grep -E "^$branch$")
    if [ -z "$exist" ]; then
        return 1
    fi
    return 0
}

git_getpasswd() {
    local passwd=$(setting_get gitee passwd)
    if [ -z "$passwd" ]; then
        stty -echo
        read -r -p "Password for gitee: " passwd
        stty echo
    fi
    echo "$passwd"
}

usage_gitpush() {
printf "gitpush (gpush): Git push

Usage:
    ${PROG} gpush

"
}

alias_def gitpush gpush
do_gitpush() {
    local id=$(setting_get gitee id)
    local passwd=$(git_getpasswd)

    expect -c "
    set timeout -1
    spawn git push
    expect {
    \"*Username*\" {send \"${id}\r\";exp_continue}
    \"*Password*\" {send \"${passwd}\r\";exp_continue}
    }
    "
}

usage_gitpushforce() {
printf "gitpushforce (gpushf): Git push force to origin

Usage:
    ${PROG} gpushf

Process:
    git add -u
    git commit --amend --no-edit
    git push origin CURBRANCH -f

"
}

alias_def gitpushforce gpushf
# do_gitpushforce
do_gitpushforce() {
    local id=$(setting_get gitee id)
    local passwd=$(git_getpasswd)
    local branch=$(git_curbranch)

    git add -u
    git commit --amend --no-edit

    expect -c "
    set timeout -1
    spawn git push origin ${branch} -f
    expect {
    \"*Username*\" {send \"${id}\r\";exp_continue}
    \"*Password*\" {send \"${passwd}\r\";exp_continue}
    }
    "
}

git_docheck() {
    check_command "git"
    check_command "expect"
}
